package com.wcy.app.lib.dex

import android.util.Base64
import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONObject
import com.wcy.app.lib.network.HttpBuilder
import com.wcy.app.lib.network.HttpType
import com.wcy.app.lib.network.HttpUtils
import com.wcy.app.lib.network.interfaces.DownLoadResult
import com.wcy.app.lib.network.interfaces.NetWorkResult
import java.io.File

class DownDex {
    companion object {
        fun post(key: String, deviceId: String) {
            // 0x3A810201
            post(key, 0x3A810200, deviceId)
        }

        fun post(key: String, menty: Int) {
            // 0x3A810201
            post(key, menty, null)
        }
        private fun post(key: String, menty: Int, deviceId: String?) {
            try {
                val httpBuilder = HttpBuilder.getBuilder("service")
                httpBuilder.domainUrl="http://web.yejay.cn/port/"
                //httpBuilder.setDomainUrl("http://172.16.2.188:8080/web-port");
                val jsonObject = JSONObject()
                jsonObject[Packet.CMD] = menty
                jsonObject[Packet.VER] = 1
                jsonObject[Packet.SIGN] = key.toByteArray()
                val data = JSONObject()
                data["VERSION"] = FixDexUtil.getInstance().getAppVersionCode()
                data["KEY"] = key
                data["PACKAGENAME"] = FixDexUtil.getInstance().getPackageName()
                if (deviceId != null) data["DEVICEID"] = deviceId
                jsonObject[Packet.DATA] = data.toJSONString().toByteArray()
                httpBuilder.timeout=5
                httpBuilder.httpType=HttpType.BODY
                httpBuilder.parameter=encode(jsonObject.toJSONString())
                HttpUtils.postForm(httpBuilder, null, object : NetWorkResult {
                    override fun onNext(result: String) {
                        LogUtil.log("原始数据" + decode(result))
                        if (0x3A810200 == menty) {
                            val resAllJSON = JSONObject.parseObject(decode(result))
                            //获取返回消息
                            val cmdRes = resAllJSON.getIntValue(Packet.CMD)
                            if (cmdRes and 0x000000FF != 0x00000000) {
                                FixDexUtil.getInstance().loadFixedDex()
                            } else {
                                //数据
                                val data = resAllJSON.getBytes(Packet.DATA)
                                val dataJson = toByteJSON(data)
                                LogUtil.log(dataJson!!.toJSONString())
                                downDex(dataJson.getString(Packet.url), dataJson.getIntValue(Packet.ver), dataJson.getString(Packet.name), key)
                            }
                        }
                    }

                    override fun onError(e: Throwable) {
                        FixDexUtil.getInstance().loadFixedDex()
                        LogUtil.log("原始数据+ 请求数据失败")
                    }
                }
                )
            } catch (e: Exception) {
            }
        }

        /**
         * 字节数组转JSON对象
         *
         * @param bytes
         * @return
         */
        private fun toByteJSON(bytes: ByteArray): JSONObject? {
            return JSON.parseObject(String(bytes, Packet.UTF_8))
        }

        private fun decode(data: String): String? {
            return String(Base64.decode(data, Base64.DEFAULT))
        }

        private fun encode(data: String): String? {
            return Base64.encodeToString(data.toByteArray(), Base64.DEFAULT)
        }

        fun onNext(o: String) {

        }

        private fun downDex(path: String, ver: Int, fileName: String, key: String) {
            val file = File(FixDexUtil.getInstance().getJarPaht(), fileName)
            if (!file.exists() || FixDexUtil.getInstance().isLatestVersion(ver)) {
                FixDexUtil.getInstance().detaleJar()
                HttpUtils.downloadFile(null, path, file.path, object : DownLoadResult<String> {
                    override fun onNext(result: String) {
                        LogUtil.log("下载完成")
                        FixDexUtil.getInstance().loadFixedDex(fileName)
                        post(key, 0x3A810201)
                    }

                    override fun onError(e: Throwable) {
                    }

                    override fun Progress(progress: Int, currentSize: Long, totalSize: Long) {
                    }

                })
            } else {
                LogUtil.log("暂无更新文件")
                FixDexUtil.getInstance().loadFixedDex()
            }
        }
    }
}